package cn.xiaolang.thread.threadlocal;

import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fuhw/Dean
 * @date 2019-07-22
 */
public class ThreadLocalWithAutoClose implements AutoCloseable {

    private static final ThreadLocal<Object> USERS = new ThreadLocal<>();

    public void set(Object object) {
        USERS.set(object);
    }

    public Object get() {
        return USERS.get();
    }

    @Override
    public void close() {
        USERS.remove();
    }

    @Test
    public void testAutoClose() {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10000; i++) {
            executor.execute(() -> {
                try (ThreadLocalWithAutoClose a = new ThreadLocalWithAutoClose()) {
                    String initValue = "dean";
                    a.set(initValue);
                    Assert.assertEquals(initValue, USERS.get());
                }
                Assert.assertNull(USERS.get());
            });
        }
    }

}
